<?php
/**
 * Note:     [Description]
 * Author:   longhui.huang <1592328848@qq.com>
 * DateTime: 2024/3/7 14:33
 */
declare(strict_types=1);

namespace App\Service\Auth;

use App\Bean\JwtUserBean;
use App\Cache\UserCache;
use App\Exception\Api\BadRequestException;
use App\Exception\Api\ModelNotFoundException;
use App\Service\BaseService;
use App\Service\DataService;
use App\Service\RoleService;
use App\Service\UserService;

class UserDetailService extends BaseService
{
    public function loadUserByUsername(string $username): JwtUserBean
    {
        /** @var UserCache $userCache */
        $userCache   = app(UserCache::class);
        $jwtUserBean = $userCache->getUserCache($username);

        if (!$jwtUserBean) {
            try {
                /** @var UserService $userService */
                $userService = app(UserService::class);
                $user        = $userService->getLoginData($username);
            } catch (ModelNotFoundException $exception) {
                throw new BadRequestException($exception->getMessage());
            }

            if (!$user) {
                throw new BadRequestException("Username: {$username} not found");
            }

            if (!$user->enabled) {
                throw new BadRequestException("账号未激活");
            }

            $jwtUserBean = new JwtUserBean();
            $jwtUserBean->setUser($user);

            /** @var DataService $dataService */
            $dataService = app(DataService::class);
            $dataScopes  = $dataService->getDeptIds($user);
            $jwtUserBean->setDataScopes($dataScopes);

            /** @var RoleService $roleService */
            $roleService = app(RoleService::class);
            $authorities = $roleService->mapToGrantedAuthorities($user);
            $jwtUserBean->setAuthorities($authorities);

            $roles = [];
            foreach ($authorities as $authority) {
                $roles[] = $authority->getAuthority();
            }
            $jwtUserBean->setRoles($roles);

            // 添加缓存数据
            $userCache->addUserCache($username, $jwtUserBean);
        }

        return $jwtUserBean;
    }


}
